$(document).ready(function() {
    let currentPage = 1;
    const pageSize = 5;

    function fetchTeachers(pageNumber) {
        $.ajax({
            url: `http://localhost:8080/teacher/getTeacherListByPage?pageNumber=${pageNumber}&pageSize=${pageSize}`,
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                displayTeachers(response.dataList);
                updatePagination(response);
            },
            error: function(xhr, status, error) {
                console.error('Error fetching teachers:', error);
            }
        });
    }

    function displayTeachers(teachers) {
        const tbody = $('#teacherTable tbody');
        tbody.empty();

        teachers.forEach(teacher => {
            const row = `
                <tr>
                    <td>${teacher.teacherID}</td>
                    <td>${teacher.name}</td>
                    <td>${teacher.gender}</td>
                    <td>${teacher.title}</td>
                    <td>${teacher.email}</td>
                    <td>${teacher.phone}</td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    function updatePagination(pageInfo) {
        const pagination = $('#pagination');
        pagination.empty();

        if (pageInfo.totalPages > 1) {
            const prevButton = $('<button>').text('上一页').prop('disabled', pageInfo.currentPage === 1);
            const nextButton = $('<button>').text('下一页').prop('disabled', pageInfo.currentPage === pageInfo.totalPages);

            prevButton.click(function() {
                if (currentPage > 1) {
                    currentPage--;
                    fetchTeachers(currentPage);
                }
            });

            nextButton.click(function() {
                if (currentPage < pageInfo.totalPages) {
                    currentPage++;
                    fetchTeachers(currentPage);
                }
            });

            pagination.append(prevButton);
            pagination.append(`<span>第 ${pageInfo.currentPage} 页，共 ${pageInfo.totalPages} 页</span>`);
            pagination.append(nextButton);
        }
    }

    // 初始加载
    fetchTeachers(currentPage);
});

